//
//  NetworkingRequest.swift
//  CrazyEstate
//
//  Created by Luiz on 2017/1/16.
//  Copyright © 2017年 liangyi. All rights reserved.
//

import UIKit
import Alamofire
import MJRefresh
import SwiftyXMLParser

let currentVersion = Bundle.main.infoDictionary?[String(kCFBundleVersionKey)] as? String ?? "0"


class NetworkingHandle: NSObject {
//    static var main = "http://47.93.228.190"
    static var main = "http://222.92.52.174:8090/" //
//    static var mainHost = "http://222.92.52.174:9080/LTCIService.asmx"
    static var mainHost = "\(main)/LTCIService.asmx"
   //static var mainHost = "http://shtl.zhongfeigou.com" + "/app/"
  // static var mainHost = "http://shtlcm.cn" + "/App/"
//        static var mainHost = "http://zba.52lianbei.com" + "/App/"

//        static var mainHost = "http://zhiboa.tstmobile.com" + "/App/"
 //           static var mainHost = "http://update.zhiboxiaoka.com" + "/App/"


//    static var mainHost = "http://zba.tstmobile.com" + "/App/"
    // POST 请求 Info
    
    
    class func toSoapMessage(methodName: String, params: String) -> String {
        var message: String = String()
        message += "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
        message += "<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://schemas.xmlsoap.org/soap/envelope/\">"
        message += "<soap12:Body>"
        message += "<\(methodName) xmlns=\"http://tempuri.org/\">"//http://xxx/webservices/ 是Webservice的namespace
        message += "\(params)"
        message += "</\(methodName)>"
        message += "</soap12:Body>"
        message += "</soap12:Envelope>"
        return message
    }
    
    static func oldfetchNetworkData(method: String, paramString: String, isAuthHide: Bool = true, isShowHUD: Bool = true, isShowError: Bool = true, hasHeaderRefresh: UIScrollView? = nil, success: @escaping (Dictionary<String, Any>) -> (), failure: @escaping (() -> ())) {
        
//        let values = ["IDNum":"320504196001170517","Password":"170517"].convertToJsonString()//"{\"IDNum\": \"320503193409092022\", \"Password\": \"092022\"}";
//        let p0 = "<CodeName>"+"loginapp"+"</CodeName>"
//        let p1 = "<json>"+values+"</json>"
        let soapMsg: String = toSoapMessage(methodName: method, params: paramString)
        
        let u = NSURL(string: "\(main)/LTCIService2.asmx")! as URL
        var re = URLRequest(url: u)
        re.setValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
        re.setValue("text/xml; charset=utf-8", forHTTPHeaderField: "Accept")
        re.setValue(String(soapMsg.count), forHTTPHeaderField: "Content-Length")
        re.httpBody =  soapMsg.data(using: String.Encoding.utf8)
        re.httpMethod = "POST"
        
        

//        var atView: UIView
//        if at is UIViewController {
//            atView = (at as! UIViewController).view
//        } else if at is UIView {
////            if let vc = (at as? UIView)?.responderViewController() {
////                atView = vc.view
////            }
//            atView = UIApplication.shared.keyWindow!
//        } else {
//            atView = UIApplication.shared.keyWindow!
//        }
        print(paramString)
        if hasHeaderRefresh == nil, isShowHUD {
            CDUtility.showHud()
//            ProgressHUD.showLoading(toView: atView)a
        }

        UIApplication.shared.isNetworkActivityIndicatorVisible = true
        Alamofire.request(re).responseString { (dataResponse) in
            UIApplication.shared.isNetworkActivityIndicatorVisible = false
            if let scrollView = hasHeaderRefresh {
                scrollView.mj_header?.endRefreshing()
                scrollView.mj_footer?.endRefreshing()
            } else if isAuthHide, isShowHUD {
                CDUtility.hidHud()
                //                ProgressHUD.hideLoading(toView: atView)
            }
            if let error = dataResponse.result.error {
                if let status = dataResponse.response?.statusCode {
                    CDUtility.showMSG(message: "\(status)-服务器访问失败")
                    //                    ProgressHUD.showNoticeOnStatusBar(message: "\(status)-服务器访问失败")
                } else {
                    CDUtility.showMSG(message: error.localizedDescription)
                    //                    ProgressHUD.showNoticeOnStatusBar(message: error.localizedDescription)
                }
                failure()
            } else {
                guard let json = dataResponse.result.value else {
                    failure()
                    CDUtility.showMSG(message: "未知错误")
                    //                    ProgressHUD.showNoticeOnStatusBar(message: "未知错误")
                    return
                }
                print("##########\(json)")
                
                if let xml = try? XML.parse(json) {
                    if let d = xml["soap:Envelope"]["soap:Body"]["ExeHNServiceResponse"]["ExeHNServiceResult"].text {
                        if let dict = d.convertToDictionary() as? Dictionary<String, Any> {
                            success(dict)
                            return
                        }
                    }
                    failure()
                } else {
                    failure()
                }
                
//                if let dictionary = json.convertToDictionary() as? Dictionary<String, Any>{
//                    success(dictionary)
//                } else {
//                    failure()
//                }
            }
        }
    }
    
    static func fetchNetworkString(method: String, paramString: String, isAuthHide: Bool = true, isShowHUD: Bool = true, isShowError: Bool = true, hasHeaderRefresh: UIScrollView? = nil, success: @escaping (String) -> (), failure: @escaping (() -> ())) {
        
        let soapMsg: String = toSoapMessage(methodName: method, params: paramString)
        
        let u = NSURL(string: mainHost)! as URL
        var re = URLRequest(url: u)
        re.setValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
        re.setValue("text/xml; charset=utf-8", forHTTPHeaderField: "Accept")
        re.setValue(String(soapMsg.count), forHTTPHeaderField: "Content-Length")
        re.httpBody =  soapMsg.data(using: String.Encoding.utf8)
        re.httpMethod = "POST"
        
        
        
        //        var atView: UIView
        //        if at is UIViewController {
        //            atView = (at as! UIViewController).view
        //        } else if at is UIView {
        ////            if let vc = (at as? UIView)?.responderViewController() {
        ////                atView = vc.view
        ////            }
        //            atView = UIApplication.shared.keyWindow!
        //        } else {
        //            atView = UIApplication.shared.keyWindow!
        //        }
        print(paramString)
        if hasHeaderRefresh == nil, isShowHUD {
            CDUtility.showHud()
            //            ProgressHUD.showLoading(toView: atView)a
        }
        
        UIApplication.shared.isNetworkActivityIndicatorVisible = true
        Alamofire.request(re).responseString { (dataResponse) in
            UIApplication.shared.isNetworkActivityIndicatorVisible = false
            if let scrollView = hasHeaderRefresh {
                scrollView.mj_header?.endRefreshing()
                scrollView.mj_footer?.endRefreshing()
            } else if isAuthHide, isShowHUD {
                CDUtility.hidHud()
                //                ProgressHUD.hideLoading(toView: atView)
            }
            if let error = dataResponse.result.error {
                if let status = dataResponse.response?.statusCode {
                    CDUtility.showMSG(message: "\(status)-服务器访问失败")
                    //                    ProgressHUD.showNoticeOnStatusBar(message: "\(status)-服务器访问失败")
                } else {
                    CDUtility.showMSG(message: error.localizedDescription)
                    //                    ProgressHUD.showNoticeOnStatusBar(message: error.localizedDescription)
                }
                failure()
            } else {
                guard let json = dataResponse.result.value else {
                    failure()
                    CDUtility.showMSG(message: "未知错误")
                    //                    ProgressHUD.showNoticeOnStatusBar(message: "未知错误")
                    return
                }
                print("##########\(json)")
                if let xml = try? XML.parse(json) {
                    if let d = xml["soap:Envelope"]["soap:Body"]["\(method)Response"]["\(method)Result"].text {
                        success(d)
                    }
                    failure()
                } else {
                    failure()
                }
            }
        }
    }
    
    static func fetchNetworkData(method: String, paramString: String, isAuthHide: Bool = true, isShowHUD: Bool = true, isShowError: Bool = true, hasHeaderRefresh: UIScrollView? = nil, success: @escaping (Dictionary<String, Any>) -> (), failure: @escaping (() -> ())) {
        
        let soapMsg: String = toSoapMessage(methodName: method, params: paramString)
        
        let u = NSURL(string: mainHost)! as URL
        var re = URLRequest(url: u)
        re.setValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
        re.setValue("text/xml; charset=utf-8", forHTTPHeaderField: "Accept")
        re.setValue(String(soapMsg.count), forHTTPHeaderField: "Content-Length")
        re.httpBody =  soapMsg.data(using: String.Encoding.utf8)
        re.httpMethod = "POST"
        
        
        //        var atView: UIView
        //        if at is UIViewController {
        //            atView = (at as! UIViewController).view
        //        } else if at is UIView {
        ////            if let vc = (at as? UIView)?.responderViewController() {
        ////                atView = vc.view
        ////            }
        //            atView = UIApplication.shared.keyWindow!
        //        } else {
        //            atView = UIApplication.shared.keyWindow!
        //        }
//        print(paramString)
        if hasHeaderRefresh == nil, isShowHUD {
            CDUtility.showHud()
            //            ProgressHUD.showLoading(toView: atView)a
        }
        
        UIApplication.shared.isNetworkActivityIndicatorVisible = true
        Alamofire.request(re).responseString { (dataResponse) in
            UIApplication.shared.isNetworkActivityIndicatorVisible = false
            if let scrollView = hasHeaderRefresh {
                scrollView.mj_header?.endRefreshing()
                scrollView.mj_footer?.endRefreshing()
            } else if isAuthHide, isShowHUD {
                CDUtility.hidHud()
                //                ProgressHUD.hideLoading(toView: atView)
            }
            if let error = dataResponse.result.error {
                if let status = dataResponse.response?.statusCode {
                    CDUtility.showMSG(message: "\(status)-服务器访问失败")
                    //                    ProgressHUD.showNoticeOnStatusBar(message: "\(status)-服务器访问失败")
                } else {
                    CDUtility.showMSG(message: error.localizedDescription)
                    //                    ProgressHUD.showNoticeOnStatusBar(message: error.localizedDescription)
                }
                failure()
            } else {
                guard let json = dataResponse.result.value else {
                    failure()
                    CDUtility.showMSG(message: "未知错误")
                    //                    ProgressHUD.showNoticeOnStatusBar(message: "未知错误")
                    return
                }
                print("##########\(json)")
                if let xml = try? XML.parse(json) {
                    if let d = xml["soap:Envelope"]["soap:Body"]["\(method)Response"]["\(method)Result"].text {
                        if let dict = d.convertToDictionary() as? Dictionary<String, Any> {
                            success(dict)
                            return
                        }
                    }
                    
                    failure()
                } else {
                    failure()
                }
            }
        }
    }

    class func toUploadPhotyoSoapMessage(methodName: String, params: String) -> String {
        var message: String = String()
        message += "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
        message += "<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://schemas.xmlsoap.org/soap/envelope/\">"
        message += "<soap12:Body>"
        message += "<\(methodName) xmlns=\"http://tempuri.org/\">"//http://xxx/webservices/ 是Webservice的namespace
        message += "\(params)"
        message += "</\(methodName)>"
        message += "</soap12:Body>"
        message += "</soap12:Envelope>"
        return message
    }

    static func uploadPhoto(method: String, paramString: String, isAuthHide: Bool = true, isShowHUD: Bool = true, isShowError: Bool = true, hasHeaderRefresh: UIScrollView? = nil, success: @escaping (Dictionary<String, Any>) -> (), failure: @escaping (() -> ())) {
        
        let soapMsg: String = toUploadPhotyoSoapMessage(methodName: method, params: paramString)
        
        let u = NSURL(string: mainHost)! as URL
        var re = URLRequest(url: u)
        re.setValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
        re.setValue("text/xml; charset=utf-8", forHTTPHeaderField: "Accept")
        re.setValue(String(soapMsg.count), forHTTPHeaderField: "Content-Length")
        re.httpBody =  soapMsg.data(using: String.Encoding.utf8)
        re.httpMethod = "POST"
        
        
        //        var atView: UIView
        //        if at is UIViewController {
        //            atView = (at as! UIViewController).view
        //        } else if at is UIView {
        ////            if let vc = (at as? UIView)?.responderViewController() {
        ////                atView = vc.view
        ////            }
        //            atView = UIApplication.shared.keyWindow!
        //        } else {
        //            atView = UIApplication.shared.keyWindow!
        //        }
        //        print(paramString)
        if hasHeaderRefresh == nil, isShowHUD {
            CDUtility.showHud()
            //            ProgressHUD.showLoading(toView: atView)a
        }
        
        UIApplication.shared.isNetworkActivityIndicatorVisible = true
        Alamofire.request(re).responseString { (dataResponse) in
            UIApplication.shared.isNetworkActivityIndicatorVisible = false
            if let scrollView = hasHeaderRefresh {
                scrollView.mj_header?.endRefreshing()
                scrollView.mj_footer?.endRefreshing()
            } else if isAuthHide, isShowHUD {
                CDUtility.hidHud()
                //                ProgressHUD.hideLoading(toView: atView)
            }
            if let error = dataResponse.result.error {
                if let status = dataResponse.response?.statusCode {
                    CDUtility.showMSG(message: "\(status)-服务器访问失败")
                    //                    ProgressHUD.showNoticeOnStatusBar(message: "\(status)-服务器访问失败")
                } else {
                    CDUtility.showMSG(message: error.localizedDescription)
                    //                    ProgressHUD.showNoticeOnStatusBar(message: error.localizedDescription)
                }
                failure()
            } else {
                guard let json = dataResponse.result.value else {
                    failure()
                    CDUtility.showMSG(message: "未知错误")
                    //                    ProgressHUD.showNoticeOnStatusBar(message: "未知错误")
                    return
                }
                print("##########\(json)")
                if let xml = try? XML.parse(json) {
                    if let d = xml["soap:Envelope"]["soap:Body"]["\(method)Response"]["\(method)Result"].text {
                        if let dict = d.convertToDictionary() as? Dictionary<String, Any> {
                            success(dict)
                            return
                        }
                    }
                    
                    failure()
                } else {
                    failure()
                }
            }
        }
    }


}


func fetchVerificationCodeCountdown(button: UIButton, timeOut: Int) -> DispatchSourceTimer {
    let timer = DispatchSource.makeTimerSource(queue: DispatchQueue.global())
    var timeout = timeOut
    timer.setEventHandler {
        if timeout <= 1 {
            timer.cancel()
            DispatchQueue.main.sync {
                button.setTitle("发送验证码", for: .normal)
                button.isEnabled = true
            }
        } else {
            DispatchQueue.main.sync {
                button.setTitle("\(timeout)秒后重发", for: .normal)
                button.isEnabled = false
            }
            timeout -= 1
        }
    }
    timer.scheduleRepeating(deadline: .now(), interval: .seconds(1))
    timer.resume()
    
    return timer
}


//import SQLite
//
//struct SQLiteManager {
//
//    private var db: Connection!
//    private let tableName = Table("LvingMusic") //表名
//    private let id = Expression<Int64>("id")      //主键
//    private let songName = Expression<String>("songName")  //列表1
//    private let singer = Expression<String>("singer") //列表2
//    private let pathPostfix = Expression<String>("pathPostfix") //列表3
//    private let time = Expression<String>("time") //列表4
//
//    private let tableName_Tags = Table("Tags") //表名
//    private let tag_id = Expression<Int64>("id")      //主键
//    private let tag_name = Expression<String>("name")      //主键
//
//
//    static var manager = SQLiteManager()
//
//    init() {
//        createdsqlite3()
//    }
//
//    //创建数据库文件
//    mutating func createdsqlite3(filePath: String = "/Documents")  {
//        let sqlFilePath = NSHomeDirectory() + filePath + "/db.sqlite3"
//        do {
//            db = try Connection(sqlFilePath)
//            try db.run(tableName.create { t in
//                t.column(id, primaryKey: true)
//                t.column(songName)
//                t.column(pathPostfix)
//                t.column(singer)
//                t.column(time)
//            })
//            try db.run(tableName_Tags.create { t in
//                t.column(tag_id, primaryKey: true)
//                t.column(tag_name)
//            })
//        } catch { print(error) }
//    }
//
//
//
//    //插入数据
//    func insert(model: LivingBGMModel){
//        do {
//            let insert = tableName.insert(songName <- model.song_name!, singer <- model.singer!, pathPostfix <- model.pathPostfix!, time <- model.time!)
//            try db.run(insert)
//        } catch {
//            print(error)
//        }
//    }
//
//    //读取数据
//    func readData() -> [LivingBGMModel] {
//        var dataArr: [LivingBGMModel] = []
//        for model in try! db.prepare(tableName) {
//            let m = LivingBGMModel()
//            m.dbId = model[id]
//            m.singer = model[singer]
//            m.song_name = model[songName]
//            m.time = model[time]
//            m.pathPostfix = model[pathPostfix]
//            dataArr.append(m)
//        }
//        return dataArr
//    }
//
//    //插入数据
//    func insertTag(model: TagsModel){
//        do {
//            let insert = tableName_Tags.insert(tag_name <- model.name!)
//            try db.run(insert)
//        } catch {
//            print(error)
//        }
//    }
//
//    //读取数据
//    func readDataTag() -> [TagsModel] {
//        var dataArr: [TagsModel] = []
//        for model in try! db.prepare(tableName_Tags) {
//            let m = TagsModel()
//            m.name = model[tag_name]
//            dataArr.append(m)
//        }
//        return dataArr
//    }
//    //更新数据
////    func updateData(dbId: Int64, old_name: String, new_name: String) {
////        let currUser = tableName.filter(id == dbId)
////        do {
////            try db.run(currUser.update(name <- name.replace(old_name, with: new_name)))
////        } catch {
////            print(error)
////        }
////
////    }
//
//    //删除数据
//    func delData(dbId: Int64) {
//        let currUser = tableName.filter(id == dbId)
//        do {
//            try db.run(currUser.delete())
//        } catch {
//            print(error)
//        }
//    }
//}

class CD_CountDown {
    fileprivate static let sharedInstance = CD_CountDown()
    fileprivate init() {}
    //提供静态访问方法
    public static var shared: CD_CountDown {
        return self.sharedInstance
    }
    ///时间倒计时标识存储，预防重复创建同一计时线程
    var notifyNames:[String] = []
}
extension CD_CountDown {
    //MARK:--- 验证码秒表倒计时 ----------
    ///验证码秒表倒计时
    open class func addVerifyCode(_ notifyName:String, maxTime: Int = 60) {
        //以notifyName为标识，不必重复创建线程
        if CD_CountDown.shared.notifyNames.contains(notifyName) {return}
        CD_CountDown.shared.notifyNames.append(notifyName)
        let toTime = Date().timeIntervalSince1970 + TimeInterval(maxTime)
        var aTime = maxTime
        let queue = DispatchQueue(label: notifyName)
        // 创建一个时间源
        let timer = DispatchSource.makeTimerSource(queue:queue)
        //循环执行，马上开始，间隔为0.1s,误差允许10微秒
        timer.scheduleRepeating(deadline: .now(), interval: .seconds(1), leeway: .milliseconds(10))
        // 设定时间源的触发事件
        timer.setEventHandler(handler: {
            aTime = Int(toTime - Date().timeIntervalSince1970)
            if aTime <= 0 {
                //timer.suspend()
                timer.cancel()
                
                DispatchQueue.main.async {
                    print("通知\(aTime)")
                    CD_CountDown.shared.notifyNames.remove(at: CD_CountDown.shared.notifyNames.index(of: notifyName)!)
                    NotificationCenter.default.post(name: NSNotification.Name.init(notifyName), object: 0)
                }
            }else{
                DispatchQueue.main.async {
                    print("通知\(aTime)")
                    NotificationCenter.default.post(name: NSNotification.Name.init(notifyName), object: aTime)
                }
            }
        })
        // 启动时间源
        timer.resume()
    }
}
